<template>
  <div class="upload-excel">
    <div class="left-box">
      <el-button
        :loading="loading"
        style="margin-left:16px;"
        size="mini"
        type="primary"
        @click="handleUpload"
      >
        点击上传
      </el-button>
    </div>
    <input
      ref="excel-upload-input"
      class="excel-upload-input"
      type="file"
      accept=".xlsx, .xls"
      @change="handleClick"
    >
    <div
      class="drop"
      @drop="handleDrop"
      @dragover="handleDragover"
      @dragenter="handleDragover"
    >
      <i class="el-icon-upload" />
      <div>将文件拖到此处</div>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'

export default {
  // 父传子要的数据
  props: {
    // 要了一个叫beforeUpload，另外一个叫onSuccess
    // 要的是函数类型
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function // eslint-disable-line
  },
  data() {
    return {
      loading: false,
      excelData: {
        header: null,
        results: null
      }
    }
  },
  methods: {
    generateData({ header, results }) {
      this.excelData.header = header
      this.excelData.results = results
      // 判断是否存在onSuccess，如果存在就调用onSuccess
      // 它相当于写的是 if (this.onSuccess)  {  this.onSuccess()   }
      this.onSuccess && this.onSuccess(this.excelData)
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('Only support uploading one file!')
        return
      }
      const rawFile = files[0] // only use files[0]

      if (!this.isExcel(rawFile)) {
        this.$message.error(
          'Only supports upload .xlsx, .xls, .csv suffix files'
        )
        return false
      }
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      // 如果为空，直接return
      if (!rawFile) return
      // 不为空调用upload
      this.upload(rawFile)
    },
    upload(rawFile) {
      // 修复不能选同一个excel的bug
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel
      // 如果没有beforeUpload，也会直接读取excel文件
      if (!this.beforeUpload) {
        this.readerData(rawFile)
        return
      }

      // 如果传了beforeUpload
      const before = this.beforeUpload(rawFile)
      if (before) {
        // 读取excel内容
        this.readerData(rawFile)
      }
    },
    readerData(rawFile) {
      // 加载动画
      this.loading = true
      // 把一些异步代码封装成promise对象
      return new Promise((resolve, reject) => {
        // 文件读取器
        const reader = new FileReader()
        // 读取完毕调用onLoad事件
        reader.onload = e => {
          // 读取的结果 --- 把读取到的二进制赋值给data了
          const data = e.target.result
          // XLSX插件有个read方法，这个方法要求传入读取到的excel的二进制
          // 就能得到表格的内容，得到的是一个对象
          const workbook = XLSX.read(data, { type: 'array' })
          // 因为一个excel文件可以有多个sheet，我们这里只要读取一个sheet的名字
          const firstSheetName = workbook.SheetNames[0]
          // 表格对象根据sheet的名字，可以取出对应这个sheet里的内容
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          // XLSX这个插件自带的，就自动能读取出内容，而且转成对象的形式
          const results = XLSX.utils.sheet_to_json(worksheet)
          this.generateData({ header, results })
          this.loading = false

          resolve()
        }
        // 读取文件，读取成二进制
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name)
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-excel {
  display: flex;
  justify-content: center;
  margin-top: 100px;

  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
  .drop,
  .left-box {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border: 1px dashed #bbb;
    width: 350px;
    height: 160px;
    font-size: 24px;
    border-radius: 5px;
    text-align: center;
    color: #bbb;
    position: relative;
    i {
      font-size: 46px;
      margin-bottom: 15px;
    }
  }
}
</style>
